from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.views import login as django_login
from django.contrib.auth import authenticate

from shop.forms import RegistrationForm, AccountForm, ErrorLabel
from shop.views.product import list as product_list_view
from shop.models import Address, UserProfile


MSG_REGISTRATION_SUCCESSFUL = u'Registration Successful. You are now logged in.'
MSG_LOGIN_SUCCESSFUL = u'You are now logged in.'
MSG_LOGOUT_SUCCESSFUL = u'You are now logged out.'
MSG_UPDATE_SUCCESSFUL = u'Update Successful.'


def login(request, template_name):
    """Adds a flash message on successful login and proceeds to
    django.contrib login

    """
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        request.flash['notice'] = MSG_LOGIN_SUCCESSFUL
    return django_login(request, template_name)


def logout(request):
    auth.logout(request)
    request.flash['notice'] = MSG_LOGOUT_SUCCESSFUL
    return redirect('/')


def register(request):
    # don't allow logged in users to register
    if request.user.is_authenticated():
        return redirect('/')

    if request.method == 'POST':
        registration_form = RegistrationForm(request.POST,
                                             error_class=ErrorLabel,
                                             label_suffix='')
        # check form
        if registration_form.is_valid():

            # create user
            registration_form.register()

            # log user in
            user = auth.authenticate(username=request.POST['username'],
                                     password=request.POST['password'])
            auth.login(request, user)

            #show message
            request.flash['notice'] = MSG_REGISTRATION_SUCCESSFUL

            # continue to desired page or to product list
            if 'next' in request.POST:
                return redirect(request.POST.get('next'))
            else:
                return redirect(product_list_view)
        else:
            output = {'form': registration_form}
            return render_to_response('register.html', output,
                                      context_instance=RequestContext(request))

    # otherwise for GET give registration form
    output = {'form': RegistrationForm(error_class=ErrorLabel, label_suffix='')}

    # set next URL if login/registration was initiated from cart page: checkout
    # for instance
    if 'next' in request.GET:
        output.update({'next': request.GET.get('next')})

    return render_to_response('register.html', output,
        context_instance=RequestContext(request))

def account(request):
    # user must be logged in
    if not request.user.is_authenticated():
        return redirect('/')

    if request.method == 'POST':
        account_form = AccountForm(request.POST,
                                             error_class=ErrorLabel,
                                             label_suffix='')

        # check form
        if account_form.is_valid(request):

            # update user
            account_form.update()

            #show message
            request.flash['notice'] = MSG_UPDATE_SUCCESSFUL

            return redirect(account)
        else:
            output = {'form': account_form}
            return render_to_response('account.html', output,
                                      context_instance=RequestContext(request))

    # get use profile
    user_profile = UserProfile.objects.get(user=request.user)

    # get default data
    default_data = {'username': user_profile.user.username,
                    'firstname': user_profile.user.first_name,
                    'lastname': user_profile.user.last_name,
                    'email': user_profile.user.email,
                    'phonenumber': user_profile.phonenumber,
                    'street_address': user_profile.shipping_address.street_address,
                    'postal_code': user_profile.shipping_address.postal_code,
                    'city': user_profile.shipping_address.city,
                    'country': user_profile.shipping_address.country}

    form =  AccountForm(initial=default_data, error_class=ErrorLabel, label_suffix='')

    # otherwise for GET give account form
    output = {'form': form}

    return render_to_response('account.html', output,
        context_instance=RequestContext(request))


